<template>
  <div>
    <div class="title-warpper">
      <div class="title">
        城市选择
        <router-link to="/">
          <div class="left">
            <!-- 返回的icon-->
            <div class="iconfont backicon">&#xe606;</div>
          </div>
        </router-link>
      </div>
    </div>
    <div class="search">
      <input v-model="keyword" class="search-input" placeholder="输入城市名或拼音" type="text" />
    </div>
    <div class="search-context" ref="wapper" v-show="keyword">
      <ul>
        <li v-for="itme of list" :key="itme.id" class="search-itme border-bottom" @click="handelCick(itme.name)">{{itme.name}}</li>
        <li v-show="hasList" class="search-itme border-bottom">没有找到匹配的数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
/* better-scroll 是一款重点解决移动端（已支持 PC）各种滚动场景需求的插件 */
import Bscroll from 'better-scroll'
export default {
  name: 'CityHeader',
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  props: ['cities'],
  methods: {
    handelCick (city) {
      this.$store.commit('change', city)
      this.$router.push('/')
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const resu = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              resu.push(value)
            }
          })
        }
        this.list = resu
      }, 100)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.wapper)
  },
  computed: {
    hasList () {
      return !this.list.length
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/config.styl'
  .title-warpper
    background: $background
    line-height: $lingheight
    color: #FFFFFF
    font-size: .32rem
    overflow: hidden
    position: relative
    .title
      text-align: center
      .left
        position: absolute
        width: .64rem
        top: 0
        left: 0
        color: #fff
        .backicon
          text-align: center
          font-size: .4rem
  .search
    height: .72rem
    padding: 0 .1rem
    background: $background
    .search-input
      width: 100%
      height: .62rem
      line-height: .62rem
      border-radius: .05rem
      text-align: center
      box-sizing: border-box
      padding: 0 .1rem
      color: #666
  .search-context
    z-index: 1
    overflow: hidden
    position: absolute
    top: 1.58rem
    left: 0
    right: 0
    bottom: 0
    background: #eee
    .search-itme
      line-height: .62rem
      padding-left: .2rem
      background: #fff
      color: #666
</style>
